<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img v-if="avatar" class="preview" :src="avatar" alt="" />
      <img v-else src="../../../assets/images/avatar.jpg" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          type="file"
          ref="inp"
          accept="image/*"
          style="display: none"
          @change="changHandler"
        />
        <el-button type="primary" @click="$refs.inp.click()" icon="el-icon-plus"
          >选择图片</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          :disabled="!avatar"
          @click="uploadAvatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    changHandler (e) {
      // 非空效验
      if (e.target.files.length === 0) return
      // FileReader 来读取文件信息
      const fr = new FileReader()
      //   readAsDataURL将flie对象转为base64字符串
      fr.readAsDataURL(e.target.files[0])
      //   读取文件是异步，要用实践来获取结果
      fr.onload = (e) => {
        this.avatar = e.target.result
      }
    },
    async uploadAvatar () {
      const { data: res } = await this.$http.patch('/my/update/avatar', {
        avatar: this.avatar
      })
      if (res.code !== 0) return
      //   this.$message.error('上传头像失败')
      //   this.$message.success('上传头像成功')
      //   调用用户最新的信息
      this.$store.dispatch('getUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 400px;
  height: 400px;
}
</style>
